<?php
/**
 *
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/12/18
 */

namespace app\admin\model;

use app\index\model\GoodsCat;
use think\Model;
/**
 * TODO 购物车Model
 * Class StoreCart
 * @package app\models\store
 */
class GoodsCart extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'goods_cart';


    protected $insert = ['add_time'];

    protected function setAddTimeAttr()
    {
        return time();
    }


    public function goods(){
        return $this->belongsTo(Goods::class,'product_id')->bind(['goods_id'=>'id','image','store_name','price','is_show','stock']);
    }

    /**
     * 添加购物车
     * @param [int]  $uid                 [用户id]
     * @param [int]  $product_id          [商品id]
     * @param integer $cart_num            [数量]
     * @param string  $product_attr_unique [属性唯一值]
     * @param integer $is_new              [1直接加入购物车购买 0 加入购物车]
     */
    public static function setCart($uid, $product_id, $cart_num = 1, $product_attr_unique = '', $is_new = 0)
    {
        if ($cart_num < 1) $cart_num = 1;
        $goods_info = Goods::where('id', $product_id)->field('id,merchant_id')->find();
        $merchant_id = $goods_info->merchant_id;
        if(!Order::checkProductStock($uid, $product_id,$cart_num,$product_attr_unique)){
            //检查商品有效性 库存等
            return exception(Order::getErrorInfo());
        }
        if ($cart = self::where('uid', $uid)->where('product_id', $product_id)->where('product_attr_unique', $product_attr_unique)->where('is_new', $is_new)->where('is_pay', 0)->where('is_del', 0)->find()) {
            if ($is_new)
                //直接购买形式已经存在，则直接重置购物数量
                $cart->cart_num = $cart_num;
            else
                //非直接购买 且已经存在则增加数量
            $cart->cart_num = bcadd($cart_num, $cart->cart_num, 0);
            $cart->add_time = time();
            $cart->save();
            return $cart;
        } else {
            $add_time = time();
            return self::create(compact('uid', 'product_id', 'cart_num', 'product_attr_unique', 'is_new', 'add_time','merchant_id'));
        }
    }

    public static function removeUserCart($uid, $ids)
    {
        return self::where('uid', $uid)->where('id', 'IN', implode(',', $ids))->update(['is_del' => 1]);
    }

    public static function getUserCartNum($uid, $type, $numType)
    {
        if ($numType) {
            return self::where('c.uid', $uid)->alias('c')->join('store_product p', 'p.id = c.product_id')->where('p.is_del',0)->where('c.type', $type)->where('c.is_pay', 0)->where('c.is_del', 0)->where('c.is_new', 0)->count();
        } else {
            return self::where('c.uid', $uid)->alias('c')->join('store_product p', 'p.id = c.product_id')->where('c.type', $type)->where('c.is_pay', 0)->where('c.is_del', 0)->where('c.is_new', 0)->sum('c.cart_num');
        }
    }

    /**
     * TODO 修改购物车库存
     * @param $cartId
     * @param $cartNum
     * @param $uid
     * @return StoreCart|bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function changeUserCartNum($cartId, $cartNum, $uid)
    {
        $count = self::where('uid', $uid)->where('id', $cartId)->count();
        if (!$count) return self::setErrorInfo('参数错误');
        $cartInfo = self::where('uid', $uid)->where('id', $cartId)->field('product_id,product_attr_unique,cart_num')->find()->toArray();
        $stock = 0;
         if ($cartInfo['product_id']) {
            //TODO 获取普通产品的库存
            $stock = Goods::getProductStock($cartInfo['product_id'], $cartInfo['product_attr_unique']);
        }
        if (!$stock) return self::setErrorInfo('暂无库存');
        if (!$cartNum) return self::setErrorInfo('库存错误');
        if ($stock < $cartNum) return self::setErrorInfo('库存不足' . $cartNum);
        if ($cartInfo['cart_num'] == $cartNum) return true;
        return self::where('uid', $uid)->where('id', $cartId)->update(['cart_num' => $cartNum]);
    }

    /**
     * 根据购物获取商品信息
     * @param  [type]  $uid     [用户id]
     * @param  string  $cartIds [购物车id]
     * @param  integer $status  [是否为立即购买 1 立即购买 0非立即购买]
     * @return [type]           [description]
     */
    public static function getUserProductCartList($uid, $cartIds = '', $status = 0)
    {
        $productInfoField = 'id,image,price,ot_price,postage,sales,stock,store_name,store_info,unit_name,is_show,is_del,cost,spec_type,goods_type,artist_id,cate_id,buy_limit';
        $model = new self();
        $valid = $invalid = [];
        $model = $model->alias('c')->field('c.*')->join('goods p', 'c.product_id = p.id')->where('c.uid', $uid)->where('c.is_pay', 0)
            ->where('c.is_del', 0);
        if (!$status) $model = $model->where('c.is_new', 0);
        if ($cartIds) $model = $model->where('c.id', 'IN', $cartIds);
        $model = $model->order('c.add_time DESC');
        $list = $model->select()->toArray(); //查找购物车信息 
        // dump($list);die;
        if (!count($list)) return compact('valid', 'invalid');
        $now = time();
        foreach ($list as $k => $cart) {
           $product = Goods::field($productInfoField)
                    ->with(['artist','cate'])->find($cart['product_id'])->toArray();
            
            $cart['productInfo'] = $product; //找到具体商品详情 
            if (!$product) {
                //商品不存在 更新未删除状态
                $model->where('id', $cart['id'])->update(['is_del' => 1]); 
                //商品删除或无库存
            } else if (!$product['is_show'] || $product['is_del'] || !$product['stock']) {
                $invalid[] = $cart; //属于无效商品
             
            }  else if (!GoodsAttr::issetProductUnique($cart['product_id'], $cart['product_attr_unique'])) {
                $invalid[] = $cart; //检查该属性的商品是否存在 若不存在属于无效商品      
            } else {
                //正常商品
                if ($cart['product_attr_unique']) {
                    $attrInfo = GoodsAttr::uniqueByAttrInfo($cart['product_attr_unique']);
                    //商品没有对应的属性
                    //已购买数量
                    $user_buy_limit = GoodsCart::where('uid', $uid)
                        ->where('product_id', $cart['product_id'])
                        ->where('is_pay', 1)
                        ->where('is_del', 0)
                        ->sum('cart_num');
                    if($product['buy_limit'] > 0 && $user_buy_limit + $cart['cart_num'] > $product['buy_limit']){
                        $invalid[] = $cart;
                    }
                    if (!$attrInfo || !$attrInfo['stock'])
                        $invalid[] = $cart;
                    else {
                        $cart['productInfo']['attrInfo'] = $attrInfo;
                        $cart['truePrice'] = (float)$attrInfo['price'];
                        $cart['trueStock'] = $attrInfo['stock'];
                        $cart['costPrice'] = $attrInfo['cost'];
                        $cart['productInfo']['image'] = empty($attrInfo['image']) ? $cart['productInfo']['image'] : $attrInfo['image'];
                        $valid[] = $cart;
                    }
                } else {
                    $cart['truePrice'] = (float)$cart['productInfo']['price'];
                    $cart['trueStock'] = $cart['productInfo']['stock'];
                    $cart['costPrice'] = $cart['productInfo']['cost'];
                    $valid[] = $cart;
                }
            }
        }
        foreach ($valid as $k => $cart) {
            if($cart['productInfo']['spec_type']==1){
                //多属性商品
                $valid[$k]['price'] = $cart['productInfo']['attrInfo']['price']; //取商品规格里的价格
                $valid[$k]['ot_price'] = $cart['productInfo']['attrInfo']['ot_price']; //取商品规格里的s售价
                $valid[$k]['bar_code'] = $cart['productInfo']['attrInfo']['bar_code']; //取商品规格里的编码
                $valid[$k]['stock'] = $cart['productInfo']['attrInfo']['stock'];//取商品规格里的库存
                $valid[$k]['sales'] = $cart['productInfo']['attrInfo']['sales'];//取商品规格里的销量
                $valid[$k]['suk'] = $cart['productInfo']['attrInfo']['suk'];//取商品规格里的sku
            }
            if ($cart['trueStock'] < $cart['cart_num']) {
                //购物车购买的数量大于商品库存取最大库存
                $cart['cart_num'] = $cart['trueStock'];
                GoodsCart::where('id', $cart['id'])->update(['cart_num' => $cart['cart_num']]);
                $valid[$k] = $cart;
            }
            $valid[$k] ['thumb'] = $cart['productInfo']['attrInfo']['image']; //缩略图取商品规格里的小图
            // unset($valid[$k]['uid'], $valid[$k]['is_del'], $valid[$k]['is_new'], $valid[$k]['is_pay'], $valid[$k]['add_time']);unset($valid[$k]['productInfo']['attrInfo']);
            unset($valid[$k]['uid'], $valid[$k]['is_del'], $valid[$k]['is_new'], $valid[$k]['is_pay'], $valid[$k]['add_time']);
        }
        return compact('valid', 'invalid');
    }

    /**
     * 拼团
     * @param $uid
     * @param string $cartIds
     * @return array
     */
    public static function getUserCombinationProductCartList($uid, $cartIds = '')
    {
        $productInfoField = 'id,image,slider_image,price,cost,ot_price,vip_price,postage,mer_id,give_integral,cate_id,sales,stock,store_name,unit_name,is_show,is_del,is_postage';
        $model = new self();
        $valid = $invalid = [];
        $model = $model->where('uid', $uid)->where('type', 'product')->where('is_pay', 0)
            ->where('is_del', 0);
        if ($cartIds) $model->where('id', 'IN', $cartIds);
        $list = $model->select()->toArray();
        if (!count($list)) return compact('valid', 'invalid');
        foreach ($list as $k => $cart) {
            $product = StoreProduct::field($productInfoField)
                ->find($cart['product_id'])->toArray();
            $cart['productInfo'] = $product;
            //商品不存在
            if (!$product) {
                $model->where('id', $cart['id'])->update(['is_del' => 1]);
                //商品删除或无库存
            } else if (!$product['is_show'] || $product['is_del'] || !$product['stock']) {
                $invalid[] = $cart;
                //商品属性不对应
//            }else if(!StoreProductAttr::issetProductUnique($cart['product_id'],$cart['product_attr_unique'])){
//                $invalid[] = $cart;
                //正常商品
            } else {
                $cart['truePrice'] = (float)StoreCombination::where('id', $cart['combination_id'])->value('price');
                $cart['costPrice'] = (float)StoreCombination::where('id', $cart['combination_id'])->value('cost');
                $cart['trueStock'] = StoreCombination::where('id', $cart['combination_id'])->value('stock');
                $valid[] = $cart;
            }
        }

        foreach ($valid as $k => $cart) {
            if ($cart['trueStock'] < $cart['cart_num']) {
                $cart['cart_num'] = $cart['trueStock'];
                $model->where('id', $cart['id'])->update(['cart_num' => $cart['cart_num']]);
                $valid[$k] = $cart;
            }
        }

        return compact('valid', 'invalid');
    }

    /**
     * 产品编号
     * @param array $ids
     * @return array
     */
    public static function getCartIdsProduct(array $ids)
    {
        return self::whereIn('id', $ids)->column('product_id', 'id');
    }

    /**
     *  获取购物车内最新一张产品图
     */
    public static function getProductImage(array $cart_id)
    {
        return self::whereIn('a.id', $cart_id)->alias('a')->order('a.id desc')
            ->join('store_product p', 'p.id = a.product_id')->value('p.image');
    }

}